package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.rmi.CORBA.Util;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: changgou_parent
 * @author: zhanzhewan
 * @create: 2020-03-30 15:40
 **/
@Controller
@RequestMapping("/oauth")
public class AuthController {

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @Autowired
    private AuthService authService;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @GetMapping("/toLogin")
    public String fds(){
        System.out.println("helo");
        return "login";
    }

    /**
     * @Description: 登录认证
     * @Param:       生成令牌
     * @return:      保存到cookie和redis
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password,HttpServletResponse response){
        System.out.println(password);
        System.out.println(username);
        // 先验证参数
        if(StringUtils.isEmpty(username)){
            return new Result(false,StatusCode.ERROR,"登录失败,请输入用户名");
        }
        if(StringUtils.isEmpty(password)){
            return new Result(false,StatusCode.ERROR,"登录失败,请输入密码");
        }
        // 生成令牌
        AuthToken token = authService.token(username, password);
        String jti = token.getJti();

        // 将令牌保存cookie
        saveJwtToCookie(jti, response);

        return new Result(true, StatusCode.OK, "登录成功",jti);
    }

    private void saveJwtToCookie(String jti, HttpServletResponse response){
        CookieUtil.addCookie(response,cookieDomain,"/","uid",jti,cookieMaxAge,false);
    }
}
